package com.example.administrator.social.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.administrator.social.model.Contact;
import com.example.administrator.social.model.User;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.exceptions.HyphenateException;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

/**
 * Created by allen on 2018/9/12 0012.
 */

public  class HttpUtils {
    public static final int Chat = 0;
    public static final int CHATTYPE_GROUP = 1;
    public static final int ChatRoom = 2;
    //public static final String HTTP_URL="http://192.168.1.105:8080/SocialWeb/";
   public static final String HTTP_URL="http://192.168.7.37:8080/SocialWeb/";
    /**
     * 发送文本消息
     * @param content   发送内容
     * @param toChatUsername  发送给某用户
     */
    public static  void sendTextMessage(String content, String toChatUsername,int chatType,EMCallBack callBack) {
        //创建一条文本消息，content为消息文字内容，toChatUsername为对方用户或者群聊的id，后文皆是如此
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
        if (chatType == CHATTYPE_GROUP)message.setChatType(ChatType.GroupChat);
        //send message
        EMClient.getInstance().chatManager().sendMessage(message);
        message.setMessageStatusCallback(callBack);
    }


    /**
     * 发送语音消息
     * @param filePath  文件路径
     * @param length    文件大小
     * @param toChatUsername  发送给某用户
     */
    public static void sendVoiceMessage(String filePath,int length,String toChatUsername,int chatType){
        //filePath为语音文件路径，length为录音时间(秒)
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
         if (chatType == CHATTYPE_GROUP) message.setChatType(ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
    }


    /**
     * 发送图片消息
     * @param imagePath   图片路径
     * @param toChatUsername  发送给某用户
     */
    public void sendImageMessage(String imagePath,String toChatUsername,int chatType){
        //imagePath为图片本地路径，false为不发送原图（默认超过100k的图片会压缩后发给对方），需要发送原图传true
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
        if (chatType == CHATTYPE_GROUP)  message.setChatType(ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
    }


    /**
     * 发送地理位置
     * @param latitude 维度
     * @param longitude  经度
     * @param locationAddress
     * @param toChatUsername
     */
    public static void sendLocationMessage(double latitude,double longitude,String locationAddress,String toChatUsername,int chatType){
       //latitude为纬度，longitude为经度，locationAddress为具体位置内容
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
        if (chatType == CHATTYPE_GROUP) message.setChatType(ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    /**
     * 发送文件
     * @param filePath  文件路径
     * @param toChatUsername  发送给某用户
     * @param chatType  聊天类型
     */
    public static void sendFileMessage(String filePath,String toChatUsername,int chatType){
        EMMessage message = EMMessage.createFileSendMessage(filePath, toChatUsername);
        // 如果是群聊，设置chattype，默认是单聊
        if (chatType == CHATTYPE_GROUP) message.setChatType(ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
    }


    /**
     * 添加好友申请
     */
    public static void sendAddRequestCmdMessage(Contact contact) {
        EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
        String action="add_request";//action可以自定义
        EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
        String toUsername = contact.getName();//发送给某个人
        cmdMsg.setTo(toUsername);
        cmdMsg.addBody(cmdBody);
        EMClient.getInstance().chatManager().sendMessage(cmdMsg);

    }



    private void getMessageHistory(){
       /* EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        //获取此会话的所有消息
        List<EMMessage> messages = conversation.getAllMessages();

        //SDK初始化加载的聊天记录为20条，到顶时需要去DB里获取更多
        //获取startMsgId之前的pagesize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
        List<EMMessage> messages = conversation.loadMoreMsgFromDB(startMsgId, pagesize);

        //监听消息状态
        //message.setMessageStatusCallback(new EMCallBack(){});

        //撤回消息
        EMClient.getInstance().chatManager().recallMessage(contextMenuMessage);

        //导入消息到数据库
        EMClient.getInstance().chatManager().importMessages(msgs);

        //获取所有会话
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();*/
    }


    private void clearUnreadMessageCount(String username){
       /* EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        //指定会话消息未读数清零
        conversation.markAllMessagesAsRead();
        //把一条消息置为已读
        conversation.markMessageAsRead(messageId);
        //所有未读消息数清零
        EMClient.getInstance().chatManager().markAllConversationsAsRead();*/
    }


    /**
     * 获取所有消息数量
     * @param username  用户名
     * @param getType 获取的数据类型：内存，本地。
     *                默认是内存
     */
    public static int getLocalMessageCount(String username,int getType){
       EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
       if(getType==0){//获取此会话在本地的所有的消息数量
           return  conversation.getAllMsgCount();

       }else if (getType == 1){
           //如果只是获取当前在内存的消息数量，调用
           return  conversation.getAllMessages().size();
       }else {
           //如果只是获取当前在内存的消息数量，调用
           return  conversation.getAllMessages().size();
       }
    }


    /**
     * 获取用户未读消息总数
     * @param username
     * @return
     */
    public static int getUnReadMessageCount(String username){
       EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
       return conversation.getUnreadMsgCount();
    }


    /**
     *
     * @param username
     * @param isSaveRecord 是否删除聊天记录
     */
    public static void deleteSessionHistory(String username,boolean isSaveRecord){
       //删除和某个user会话，如果需要保留聊天记录，传false
        EMClient.getInstance().chatManager().deleteConversation(username, isSaveRecord);
    }

    /**
     *  删除当前会话的某条聊天记录
     * @param username 用户名
     * @param msgId  消息ID
     */
    public static void deleteSessionOneRecord(String username,String msgId){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        conversation.removeMessage(msgId);
    }


    /**
     * 分页加载
     */
    public static void getPagingMessageHistory(){
      /* try {
            EMClient.getInstance().chatManager().fetchHistoryMessages(
                    toChatUsername, EaseCommonUtils.getConversationType(chatType), pagesize, "");
            final List<EMMessage> msgs = conversation.getAllMessages();
            int msgCount = msgs != null ? msgs.size() : 0;
            if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
                String msgId = null;
                if (msgs != null && msgs.size() > 0) {
                    msgId = msgs.get(0).getMsgId();
                }
                conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
            }
            messageList.refreshSelectLast();
        } catch (HyphenateException e) {
            e.printStackTrace();
        }*/
    }


/*  发送扩展消息
    public static void sendExpanedeMessage(){

        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        // 增加自己特定的属性
        message.setAttribute("attribute1", "value");
        message.setAttribute("attribute2", true);
        ...
        EMClient.getInstance().chatManager().sendMessage(message);

        //接收消息的时候获取到扩展属性
        //获取自定义的属性，第2个参数为没有此定义的属性时返回的默认值
        message.getStringAttribute("attribute1",null);
        message.getBooleanAttribute("attribute2", false);
    }*/


/*okHttp------------------↓-------------*/

    /**
     * okhttp 文件上传
     * @param context
     * @param url
     * @param map
     * @param file
     */
    public static void postTextImageFile(Context context, final String url, final Map<String, String> map, File file,Callback callback) {
        OkHttpClient client = new OkHttpClient();
        // form 表单形式上传
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if(file != null){
            // MediaType.parse() 里面是上传的文件类型。
            RequestBody body = RequestBody.create(MediaType.parse("image*//*"), file);
            String filename = file.getName();
            // 参数分别为， 请求key ，文件名称 ， RequestBody
            requestBody.addFormDataPart("header_image", file.getName(), body);
        }
        if (map != null) {
            // map 里面是请求中所需要的 key 和 value
            for (Map.Entry entry : map.entrySet()) {
                requestBody.addFormDataPart(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
            }
        }
        okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(requestBody.build()).tag(context).build();
        // readTimeout("请求超时时间" , 时间单位);
        client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(callback);
    }


    /**
     * 获取未读消息数量
     * @param username
     * @return
     */
    public static int getMessageUnreadCount(String username){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        return conversation.getUnreadMsgCount();
    }


    public static void clearMessageUnreadCount(String username,String messageId){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        //指定会话消息未读数清零
        conversation.markAllMessagesAsRead();
        //把一条消息置为已读
        conversation.markMessageAsRead(messageId);
        //所有未读消息数清零
        EMClient.getInstance().chatManager().markAllConversationsAsRead();
    }


    /**
     * 指定会话未读数清零
     * @param userName
     */
    public static void markAllMessagesAsRead(String userName){
        EMConversation  conversation = EMClient.getInstance().chatManager().getConversation(userName);
        conversation.markAllMessagesAsRead();
    }

    /**
     * 所有未读消息数清零
     */
    public static void markAllConversationsAsRead(){
        EMClient.getInstance().chatManager().markAllConversationsAsRead();
    }

    /**
     * 把一条消息置为已读
     * @param userName
     * @param messageId
     */
    public static void markMessageAsRead(String userName , String messageId){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(userName);
        if (conversation!=null){
            conversation.markMessageAsRead(messageId);
        }
    }

    public static  List<EMMessage> getAllMessages(String userName){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(userName);
        //获取此会话的所有消息
        if(conversation!=null){
            return   conversation.getAllMessages();
        }
        return  null;
        //SDK初始化加载的聊天记录为20条，到顶时需要去DB里获取更多
        //获取startMsgId之前的pagesize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
        //List<EMMessage> messages = conversation.loadMoreMsgFromDB(startMsgId, pagesize);
    }
}
